#include "kestringtoast.h"

#include <QTimer>
#include <QFont>
#include <QRect>
#include <QRectF>
#include <QPainter>
#include <QSizePolicy>

#include <QDebug>

#include "../../uitools/vhc/constview4fun.h"
#include "../../uitools/vhc/constview4id.h"



KeStringToast::KeStringToast(const QString &text,QWidget *parent)
    : QWidget{parent}
    ,bgColor{Default_Background}
    ,textColor(0xff5e5e5e)
    ,labelText{text}
{
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint | Qt::Popup);
    setAttribute(Qt::WA_TranslucentBackground);
//窗口设置为Qt::Popup时, window7下会自带一个阴影.

    int nLabelWidth,   nLabelHeight;
    QFont font;
    font.setPointSize(TextSize_Toast_Default);
    QFontMetrics fontMetrics(font);
    QRect rect = fontMetrics.boundingRect(text);
    nLabelWidth = 16 + rect.width();
    nLabelHeight = 12 + rect.height();
    QSizePolicy sizePoFixed(QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed);
    sizePoFixed.setHorizontalStretch(0);
    sizePoFixed.setVerticalStretch(0);
    sizePoFixed.setHeightForWidth(false);

    setSizePolicy(sizePoFixed);
    setFixedSize(nLabelWidth,nLabelHeight);
}

KeStringToast::~KeStringToast()
{

}

void KeStringToast::showAt(int msec,const QPoint &point)
{
    show();
    move(point);
    // QTimer::singleShot(msec,this,SLOT(timeoutClose()));
    QTimer::singleShot(msec,this,&KeStringToast::timeoutClose);
}

void KeStringToast::timeoutClose()
{
    deleteLater();
}

void KeStringToast::mousePressEvent(QMouseEvent *)
{
    // setAttribute(Qt::WA_NoMouseReplay);
    // setVisible(false);
    close();

}

void KeStringToast::paintEvent(QPaintEvent *)
{
    if(isVisible())
    {
        qreal radius = 6;

        int widthWindow ,heightWidow;
        QSize rectSize = size();

        QPainter painter(this);

        painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing |QPainter::VerticalSubpixelPositioning);


        widthWindow  = rectSize.width();
        heightWidow = rectSize.height();

        QRectF _rectF(0,0,widthWindow ,heightWidow);

        painter.fillRect(0,0,widthWindow ,heightWidow,Qt::transparent);


        painter.setPen(Qt::NoPen);
        QBrush brushFill(QColor(QRgba64::fromArgb32(bgColor)),Qt::SolidPattern);

        painter.setBrush(brushFill);

        painter.drawRoundedRect(_rectF,radius,radius);

        QBrush brushText(QColor(QRgba64::fromArgb32(textColor)),Qt::SolidPattern);
        QPen penText(brushText,1.0f, Qt::SolidLine);

        painter.setPen(penText);

        QFont font;
        font.setPointSize(TextSize_Toast_Default);
        painter.setFont(font);

        painter.drawText(_rectF ,Qt::AlignCenter,labelText);
    }



}
